package com.cxd.blog.service.Thread;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxd.blog.mapper.ArticleMapper;
import com.cxd.blog.model.entity.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Author: PGTWO
 * @Version: 1.0
 * @Date: 2021/9/8 23:38
 * @Description: 线程池中更新
 */
@Component
@Slf4j
public class ThreadService {

    /**
     * 在线程池中进行操作不影响主线程
     *
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        Article articleUpdate = new Article();
        Integer viewCounts = article.getViewCounts();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaQueryWrapper<Article> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        //为了多线程下 线程安全？？
        updateWrapper.eq(Article::getViewCounts, viewCounts);
        articleMapper.update(articleUpdate, updateWrapper);
        try {
            //休眠5s，使之不会影响主线程
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
